package com.yq.order.http;

import okhttp3.OkHttpClient;

import java.util.concurrent.TimeUnit;

import okhttp3.logging.HttpLoggingInterceptor;
import sun.rmi.runtime.Log;

/**
 * Created by Administrator on 2015/10/13. modified by yiqile-21 20160512
 * <p/>
 * 更新jar包版本，添加网络超时设置(2.5以前不支持网络超时设置，默认一直请求，现为3.2版本)
 */
public class OkHttpClientManager {

    private static OkHttpClient client = null;
    private static OkHttpClient.Builder builder = null;

    private OkHttpClientManager() {
    }

    public synchronized static OkHttpClient getClient() {
        if (client == null) {
            if (builder == null) {
                builder = new OkHttpClient.Builder();
            }
            //okhttp日志打印
            HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new OkHttpLogger());
            logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addNetworkInterceptor(logInterceptor);
            client = builder.connectTimeout(20, TimeUnit.SECONDS)
                    .readTimeout(20, TimeUnit.SECONDS)
                    .build();
        }
        return client;
    }

    /**
     * 日志打印类
     */
    private static class OkHttpLogger implements HttpLoggingInterceptor.Logger {
        public void log(String message) {
            System.out.println(message);
        }
    }

}